"use strict";
Object.defineProperty(exports, "__esModule", {value: true});
const axios_1 = require("axios");
const dayjs = require("dayjs");
const CryptoJs = require("crypto-js");
const he = require("he");

const api_host = "202.63.172.66:5862";
const api_query_time = "2145835633";
const api_query_token = "9317fb5c87e831f8a38feaecf309ca13";
const api_query_platform = "qq";
const api_query_version = "2.4.1";
const api_header_sign = "15e84be1ee872552a6fe32d9ffa86b3c";
const api_header_Fing = "add45a7087ff628b951219bee85ec820";
const key = "asg#w@!aasdgs2345asga-1_s!as==g";

const headers = {
    "user-agent": "Mozilla/5.0 (Linux; Android 14; 23013RK75C Build/UKQ1.230804.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/118.0.0.0 Mobile Safari/537.36 uni-app Html5Plus/1.0 (Immersed/34.285713)",
    "x-Requested-With": "com.itingshu.hearbook",
    "Accept": "application/json",
    "Content-Type": "application/x-www-form-urlencoded",
    "sign": api_header_sign,
    "Fing": api_header_Fing,
    "Host": api_host,
    "Connection": "Keep-Alive",
};

function getUnixTime() {
    const time = dayjs(new Date()).unix();
    return time + 10;
}

function getToken(bookid, chapterID, time) {
    const v = CryptoJs.MD5(bookid + "-----" + chapterID).toString();
    return CryptoJs.MD5(key + "-" + v + "-" + time).toString();
}

function getTopListUrl(orderid) {
    return `http://${api_host}/api/apps/topList?platform=${api_query_platform}&pagesize=10&orderid=${orderid}&page=1&time=${api_query_time}&token=${api_query_token}&appVersion=${api_query_version}`;
}

function getSheetSearchUrl(keyword, page) {
    return `http://${api_host}/api/apps/cloudsearch?platform=${api_query_platform}&key=${encodeURIComponent(keyword)}&type=4&limit=30&offset=${page}&time=${api_query_time}&token=${api_query_token}&appVersion=${api_query_version}`;
    // return `http://${api_host}/api/apps/cloudsearch?platform=${api_query_platform}&key=${encodeURIComponent(query)}&type=4&limit=30&offset=1&types=marknum&time=${api_query_time}&token=${api_query_token}&appVersion=${api_query_version}`;
}

function getBookInfoUrl(id, offset, size) {
    if (offset === 1) {
        return `http://${api_host}/api/apps/bookinfo?id=${id}&platform=${api_query_platform}&limit=${size}&offset=${offset}&time=${api_query_time}&token=${api_query_token}&appVersion=${api_query_version}`;
    } else {
        return `http://${api_host}/api/apps/bookdir?id=${id}&limit=${size}&offset=${offset}&sorttype=asc&time=${api_query_time}&token=${api_query_token}&appVersion=${api_query_version}`;
    }
}

function getAlbumUrl(id, page) {
    return `http://${api_host}/api/apps/categorylist?platform=${api_query_platform}&id=${id}&limit=20&offset=${page}&orderid=1&isover=0&chapternum=0&time=${api_query_time}&token=${api_query_token}&appVersion=${api_query_version}`;
}

function formatTopItem(result) {
    return {
        id: (result.novel) ? result.novel.id : null,
        title: (result.novel) ? result.novel.name : null,
        coverImg: (result.novel) ? result.novel.cover : null,
        artwork: (result.novel) ? result.novel.cover : null
    };
}

function formatAlbum(result) {
    return {
        id: (result.novel) ? result.novel.id : null,
        title: ((result.novel) ? result.novel.name : null),
        description: (result.novel) ? result.novel.intro : null,
        album: ((result.category) ? result.category.name : null),
        artist: ((result.novel && result.novel.isover === "1") ? "完结" : "连载") + ((result.novel) ? '-' + result.novel.boyinname : null),
        artwork: (result.novel && result.novel.cover) ? result.novel.cover : result.novel.covers,
        // duration: durationToSec(result.duration),
        tags: (result.novel && result.novel.boyinname) ? result.novel.boyinname.split(",") : [],
        date: (result.utime) ? result.utime.substring(0, 10) : null,
        worksNum: (result.last) ? result.last.sign : 0,
    };
}

/**
 * 排行榜
 * @returns {Promise<({data: *[], title: string}|{data: *[], title: string}|{data: *[], title: string}|{data: *[], title: string}|{data: *[], title: string})[]>}
 */
async function getTopLists() {
    const order0 = {
        title: "最新",
        data: await getTopListItems('0')
    };
    const order1 = {
        title: "人气",
        data: await getTopListItems('1')
    };
    const order2 = {
        title: "新书",
        data: await getTopListItems('2')
    };
    const order3 = {
        title: "推荐",
        data: await getTopListItems('3')
    };
    const order4 = {
        title: "收藏",
        data: await getTopListItems('4')
    };
    return [order0, order1, order2, order3, order4];
}

/**
 * 排行榜明细
 * @param orderid
 * @returns {Promise<*[]>}
 */
async function getTopListItems(orderid) {
    const url = getTopListUrl(orderid);
    const res = (await axios_1.default.get(url, {
        headers: headers
    })).data;
    const resultList = [];
    res.data.map(v => resultList.push(formatTopItem(v)));
    return resultList;
    // return [
    //     {
    //         id: "popular/precious?page_size=100&page=1",
    //         title: "入站必刷"+getTopListUrl(orderid),
    //         coverImg: null,
    //     },
    // ];
}

/**
 * 排行榜明细播放列表
 * @param topListItem
 * @returns {Promise<{albumItem: {worksNum: *}, isEnd: boolean, musicList: *}>}
 */
async function getTopListDetail(topListItem) {
    return await getAlbumInfo(topListItem, 1, 100);
}

/**
 * 搜索
 * @param keyword
 * @param page
 * @param type
 * @returns {Promise<{data: *, isEnd: boolean}>}
 */
async function search(keyword, page, type) {
    if (type === "album") {
        return await searchAlbum(keyword, page);
    }
}

/**
 * 搜索专辑
 * @param keyword
 * @param page
 * @returns {Promise<{data: *, isEnd: boolean}>}
 */
async function searchAlbum(keyword, page) {
    const url = getSheetSearchUrl(keyword, page);
    const res = (await axios_1.default.get(url, {
        headers: headers
    })).data;
    return {
        isEnd: false,
        data: res.data.map(formatAlbum)
    };
}

/**
 * 搜索里获取专辑列的播放列表
 * @param albumItem
 * @param page
 * @param size
 * @returns {Promise<{albumItem: {worksNum: *}, isEnd: boolean, musicList: *}>}
 */
async function getAlbumInfo(albumItem, page = 1, size = 30) {
    const url = getBookInfoUrl(albumItem.id, page, size);
    const res = (await axios_1.default.get(url, {
        headers: headers
    })).data;

    const total = (page === 1) ? res.playlist.chapterlist.total : res.total;
    const playlist = (page === 1) ? res.playlist.chapterlist.playlist : res.playlist;
    return {
        isEnd: page * size >= total,
        albumItem: {
            worksNum: total,
        },
        musicList: playlist.map((result) => {
            return {
                id: result.id,
                title: (result.name) ? result.name.trim() : null,
                artist: result.zhubo,
                album: "album",
                album_id: null,
                album_audio_id: null,
                artwork: albumItem.artwork,
                "320hash": ["320hash"],
                sqhash: "sqhash",
                origin_hash: "origin_hash",
                bookid: result.bookid,
                chapterID: result.id
            };
        }),
    };
    // return {
    //     isEnd: true,
    //     albumItem: {
    //         worksNum: 1,
    //     },
    //     musicList: [{
    //             id: '111',
    //             title: "title",
    //             artist: "artist",
    //             album: "album",
    //             album_id: null,
    //             album_audio_id:null,
    //             artwork: albumItem.artwork,
    //             "320hash": ["320hash"],
    //             sqhash: "sqhash",
    //             origin_hash: "origin_hash",
    //     }],
    // };
}

/**
 * 获取热门歌单标签列表
 * @returns {Promise<{pinned: [{digest: string, id: string, title: string},{digest: string, id: string, title: string},{digest: string, id: string, title: string}], data: [{data: [{digest: string, id: string, title: string},{digest: string, id: string, title: string},{digest: string, id: string, title: string},{digest: string, id: string, title: string},{digest: string, id: string, title: string},null,null,null,null,null,null], title: string}]}>}
 */
async function getRecommendSheetTags() {
    const data = [{
        title: "分类",
        data: [
            {
                id: "12",
                title: "官场商战",
                digest: "10000",
            },
            {
                id: "3",
                title: "综艺娱乐",
                digest: "10000",
            },
            {
                id: "8",
                title: "儿童故事",
                digest: "10000",
            },
            {
                id: "4",
                title: "长篇评书",
                digest: "10000",
            },
            {
                id: "9",
                title: "网游竞技",
                digest: "10000",
            },
            {
                id: "2",
                title: "相声戏曲",
                digest: "10000",
            },
            {
                id: "6",
                title: "百家讲坛",
                digest: "10000",
            },
            {
                id: "15",
                title: "人物传记",
                digest: "10000",
            },
            {
                id: "16",
                title: "通俗文学",
                digest: "10000",
            },
            {
                id: "17",
                title: "经典纪实",
                digest: "10000",
            },
            {
                id: "14",
                title: "其他有声",
                digest: "10000",
            }
        ]
    }];
    const pinned = [
        {
            id: "1",
            title: "玄幻修真",
            digest: "10000",
        },
        {
            id: "11",
            title: "灵异惊悚",
            digest: "10000",
        },
        {
            id: "7",
            title: "军事历史",
            digest: "10000",
        }
    ];
    return {
        pinned,
        data
    };
}

/**
 * 获取热门歌单标签的播放列表
 * @param tag
 * @param page
 * @returns {Promise<{data: *, isEnd: (boolean)}>}
 */
async function getRecommendSheetsByTag(tag, page) {
    const url = getAlbumUrl(tag.id || 0, page);
    const res = (await axios_1.default.get(url, {
        headers: headers
    })).data;
    return {
        isEnd: (res.playlists && res.playlists.more) ? true : false,
        data: res.playlists.map(formatAlbum),
    };
}

/**
 * 获取热门歌单标签的播放列表
 * @param tag
 * @param page
 * @returns {Promise<{data: *, isEnd: (boolean)}>}
 */
async function getMusicSheetInfo(sheet, page) {
    return await getAlbumInfo(sheet, page);
    // return {
    //     isEnd: true,
    //     albumItem: {
    //         worksNum: 1,
    //     },
    //     musicList: [{
    //             id: '111'+sheet.id,
    //             title: "title",
    //             artist: "artist",
    //             album: "album",
    //             album_id: null,
    //             album_audio_id:null,
    //             artwork: "artwork",
    //             "320hash": ["320hash"],
    //             sqhash: "sqhash",
    //             origin_hash: "origin_hash",
    //     }],
    // };
}

/**
 * 获取音频播放链接
 * @param musicItem
 * @param quality
 * @returns {Promise<{artwork, url: string}>}
 */
async function getMediaSource(musicItem, quality) {
    const time = getUnixTime();
    const token = getToken(musicItem.bookid, musicItem.chapterID, time);
    return {
        artwork: musicItem.artwork,
        url: `http://${api_host}/api/ptcms/chapterPlays?bookID=${musicItem.bookid}&chapterID=${musicItem.chapterID}&token=${token}&time=${time}`
    };
}

module.exports = {
    platform: "爱听书",
    appVersion: ">=0.0",
    version: "0.0.1",
    author: "zcosen",
    cacheControl: "no-cache",
    srcUrl: "https://gitee.com/zcoson/static/raw/master/music-free/plugins/aitingahu-0.0.1.js",
    // primaryKey: ["id", "aid", "bvid", "cid"],
    // hints: {
    //     importMusicSheet: [
    //         "爱听书 移动端：APP点击我的，空间，右上角分享，复制链接，浏览器打开切换桌面版网站，点击播放全部视频，复制链接",
    //         "爱听书 H5/PC端：复制收藏夹URL，或者直接输入ID即可",
    //         "非公开收藏夹无法导入，编辑收藏夹改为公开即可",
    //         "导入时间和歌单大小有关，请耐心等待",
    //     ],
    // },
    // supportedSearchType: ["music", "album", "artist", "sheet"],
    supportedSearchType: ["album"],
    search,
    getAlbumInfo,
    getRecommendSheetTags,
    getRecommendSheetsByTag,
    getMusicSheetInfo,
    // getTopLists,
    // getTopListDetail,
    getMediaSource,
};

// const result = getMediaSource({
//     bookid: 30628,
//     chapterID: 192099
// });
// console.log(result);

const result = getMusicSheetInfo('0');
console.log(result);

// console.log(CryptoJs.MD5('123').toString())

//83a580efe42842e4f7109ab37b3ed374
// console.log(getToken(30628, 192099, 2145835971));
// const time = dayjs(new Date()).unix();
// console.log(dayjs.unix(time).format("YY-MM-DD HH:mm:ss"));
// console.log(dayjs.unix(time + 10).format("YY-MM-DD HH:mm:ss"));
